﻿using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace AB.Common
{
    /// <summary>
    /// XML操作帮助类
    /// </summary>
    public static class XMLHelper
    {
        /// <summary>
        /// 序列化对象为XML
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static string XMLSerialize<T>(T entity)
        {
            StringBuilder buffer = new StringBuilder();

            XmlSerializer serializer = new XmlSerializer(typeof(T));
            using (TextWriter writer = new StringWriter(buffer))
            {
                serializer.Serialize(writer, entity);
            }
            return buffer.ToString();
        }
        /// <summary>
        /// 反序列化XML为对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="str"></param>
        /// <returns></returns>
        public static T XMLDeserialize<T>(string str)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            T model;
            using (TextReader reader = new StringReader(str))
            {
                model = (T)serializer.Deserialize(reader);
            }
            return model;
        }
        /// <summary>
        /// 获取XML文档节点的值
        /// </summary>
        /// <param name="xml"></param>
        /// <param name="TagName"></param>
        /// <param name="index"></param>
        /// <returns></returns>
        public static string GetElementValue(this XmlDocument xml, string TagName, int index = 0)
        {
            XmlNode node = GetXmlNode(xml, TagName, index);
            if (node != null)
            {
                return node.InnerText;
            }
            return null;
        }
        /// <summary>
        /// 获取XML文档节点
        /// </summary>
        /// <param name="xml"></param>
        /// <param name="TagName"></param>
        /// <param name="index"></param>
        /// <returns></returns>
        public static XmlNode GetXmlNode(this XmlDocument xml, string TagName, int index = 0)
        {
            if (xml != null)
            {
                XmlNodeList list = xml.GetElementsByTagName(TagName);
                if (list != null && list.Count > 0)
                {
                    if (index >= 0 && index < list.Count)
                    {
                        XmlNode node = list.Item(index);
                        return node;
                    }
                }
            }
            return null;
        }
    }
}
